package com.itheima.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import com.itheima.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author：cxl
 * @Package：com.itheima.aop.annotation
 * @Project：web-project
 * @name：OperationAspect
 * @Date：2025/10/7 12:24
 * @Filename：OperationAspect
 */
@Slf4j
@Aspect
@Component
public class OperationAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    // ✅ 注入 Spring Boot 自动配置好的 ObjectMapper
    @Autowired
    private ObjectMapper objectMapper;

    @Around("@annotation(com.itheima.aop.annotation.LogOperater)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        OperateLog operateLog = new OperateLog();
        //获取当前登录用户
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        //设置操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //设置操作类名
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        //操作方法名
        operateLog.setMethodName(joinPoint.getSignature().getName());
        //方法参数
        operateLog.setMethodParams(objectMapper.writeValueAsString(joinPoint.getArgs()));

        try {
            result = joinPoint.proceed();
            long end = System.currentTimeMillis();
            //操作耗时
            operateLog.setCostTime(end - start);
            if (result != null){
                operateLog.setReturnValue(result.toString());
            }
        } catch (Exception e) {
            throw e;
        } finally {
            //保存操作日志到数据库表中
            operateLogMapper.insert(operateLog);
        }
        log.info("操作日志：{}", log);
        return result;
    }
}
